package com.example.demo.service;

import com.example.demo.mapper.CollegeDao;
import com.example.demo.mapper.CourseDao;
import com.example.demo.domain.dao.TeacherCourse;
import com.example.demo.domain.result.CourseDataResult;
import com.example.demo.domain.result.helper.Class;
import com.example.demo.domain.result.helper.Classroom;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author lizijian
 */
@Service
public class CourseService {

  @Autowired
  private Gson gson;

  @Autowired
  private CourseDao courseDao;

  @Autowired
  private CollegeDao collegeDao;

  public List<String> getTeacherName(String teacherName){
    teacherName+="%";
    return courseDao.getTeacherName(teacherName);
  }

  public List<String> getCoursesByTeacherName(String teacherName){
    return courseDao.getCourseByTeacherName(teacherName);
  }

  public void deleteTeacherCourse(){
    courseDao.deleteTeacherCourse();
  }

  public List<CourseDataResult> getCourseData(String teacherName,String courseName){
    ArrayList<CourseDataResult> result=new ArrayList<>(10);
    List<TeacherCourse> teacherCourse = courseDao.getTeacherCourse(courseName, teacherName);
    for (TeacherCourse course : teacherCourse) {
      String classesJson = course.getClasses();
      String[] classes = gson.fromJson(classesJson, String[].class);
      ArrayList<Class> classArrayList=new ArrayList<>(5);
      for (String aClass : classes) {
        String college = collegeDao.getCollegeByClass(aClass);
        classArrayList.add(new Class(aClass,college));
      }
      String weeksJson = course.getWeeks();
      Set<Integer> weeks =gson.fromJson(weeksJson, new TypeToken<Set<Integer>>() {
      }.getType());
      Integer classroomId = courseDao.getClassroomId(course.getClassroom(), 1);
      result.add(new CourseDataResult(classArrayList,weeks, course.getDay(), course.getLesson(),new Classroom(classroomId,course.getClassroom())));
    }
    return result;
  }

}
